const { HttpException } = require('../core/exception')

const catchError = async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    const isEnv = global.config.env === 'dev'
    const isHttpException = error instanceof HttpException
    if (isEnv && !isHttpException) {
      throw error
    }
    if (isHttpException) {
      ctx.status = error.code
      ctx.body = {
        url: `Request method is ${ ctx.method } at ${ ctx.path }`,
        errCode: error.errCode,
        errMsg: error.errMsg
      }
    } else {
      ctx.status = 500
      ctx.body = {
        url: `Request method is ${ ctx.method } at ${ ctx.path }`,
        errCode: 99999,
        errMsg: 'An error occurred on the server O(∩_∩)O~~'
      }
    }
  }
}

module.exports = catchError
